package com.acme.domain.usermap;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Logger;

public class UsersResponse {

	private final static int QUEUE_SIZE = 10;
	private static Map< SocketChannel, ArrayBlockingQueue<Object> > responseMap = new HashMap<SocketChannel,ArrayBlockingQueue<Object>>();
	private static Map< String, SocketChannel> channelMap = new HashMap< String, SocketChannel>();
	private static Logger userLogger = Logger.getLogger(UsersResponse.class.getName());
	
	public static void createUser(String username,SocketChannel channel){
		if (channelMap.containsKey(username)){
			responseMap.remove(channel);
		}
		channelMap.put(username, channel);
		responseMap.put(channel, new ArrayBlockingQueue<Object>(QUEUE_SIZE));
	}
	
	public static void addResponse(String username, Object response){
		try {
			SocketChannel s = channelMap.get(username);
			responseMap.get(s).put(response);
		} catch (InterruptedException e) {
			userLogger.warning(e.getMessage());
		} catch (NullPointerException e){
			userLogger.warning("Exception caught in user database");
		}
	}
	
	public static SocketChannel getSocketChannel(String username){
		return channelMap.get(username);
	}
	
	public static Object pollResponse(SocketChannel channel){
		try {
			if ( responseMap.get(channel).isEmpty() ){
				return null;
			} else {
				return responseMap.get(channel).poll();
			}
		}catch (NullPointerException ex){
			return null;
		}
	}
	
}
